package com.ijiuchuang.jc_localization.model.settings;

import com.ijiuchuang.jc_localization.app.Config;
import com.ijiuchuang.jc_localization.bean.lite.Map;
import com.ijiuchuang.jc_localization.bean.lite.Setts;
import com.ijiuchuang.jc_localization.contract.settings.SettsLocationContract;
import com.litesuits.orm.LiteOrm;
import com.litesuits.orm.db.assit.QueryBuilder;

import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;
import rx.functions.Func1;


/**
 * Created by Veev on 2016/6/20
 *
 * @link 384506557@qq.com
 */
public class SettsLocationModel implements SettsLocationContract.Model {

    private LiteOrm liteOrm = Config.liteOrm;

    /*@Override
    public void getDefaultScene(GetOneListener<Map> listener) {
        QueryBuilder<Setts> settsQueryBuilder = new QueryBuilder<>(Setts.class)
                .whereEquals(Setts.COL_KEY, Setts.SETTINGS_MAP_SCENE);
        List<Setts> list = liteOrm.query(settsQueryBuilder);
        if (list.isEmpty()) {
            listener.onFailure(0, "Not Found!");
        } else {
            Map map = liteOrm.queryById(list.get(0).getValueLong(), Map.class);
            if (map != null) {
                listener.onSuccess(map);
            } else {
                listener.onFailure(0, "Not Found!");
            }
        }
    }*/

    @Override
    public void getDefaultScene(Subscriber<Map> subscriber) {
        Observable
                .create(new Observable.OnSubscribe<List<Setts>>() {
                    @Override
                    public void call(Subscriber<? super List<Setts>> subscriber) {
                        QueryBuilder<Setts> settsQueryBuilder = new QueryBuilder<>(Setts.class)
                                .whereEquals(Setts.COL_KEY, Setts.SETTINGS_MAP_SCENE);
                        List<Setts> list = liteOrm.query(settsQueryBuilder);
                        subscriber.onNext(list);
                    }
                })
                .filter(new Func1<List<Setts>, Boolean>() {
                    @Override
                    public Boolean call(List<Setts> list) {
                        return !list.isEmpty();
                    }
                })
                .map(new Func1<List<Setts>, Map>() {
                    @Override
                    public Map call(List<Setts> list) {
                        Map map = liteOrm.queryById(list.get(0).getValueLong(), Map.class);
                        return map;
                    }
                })
                .filter(new Func1<Map, Boolean>() {
                    @Override
                    public Boolean call(Map map) {
                        return map != null;
                    }
                })
                .subscribe(subscriber);
    }
}
